<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import MdEditor from "@/components/MdEditor.vue";
import {
  IconPlus,
  IconDelete,
  IconSettings,
  IconCodeSquare
} from "@arco-design/web-vue/es/icon";
import {QuestionAddRequest} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import {addQuestion, getOldQuestion, updateQuestion} from "@/request/request";
import {useRoute} from "vue-router";

const form = ref({
  id: '',
  answer: '',
  content: '',
  judgeCase: [
    { input: '', output: '' }
  ],
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 1000,
    timeLimit: 1000,
  },
  tags: [],
  title: ''
} as QuestionAddRequest);

const handleSubmit = (data: any) => {
  //console.log(data);
}

const route = useRoute()
// 如果路由地址包含update，就视为更新页面
const updatePage = route.path.includes('update')
/**
 * 根据题目id获取老的数据
 */
const loadOldData = async () => {
  const id = route.query.id
  if (!id){
    return
  }
  const res = await getOldQuestion(id)
  if (res.data.code === 0){
    form.value = res.data.data as any
    if (!form.value.judgeCase){
      form.value.judgeCase = [
        { input: '', output: '' }
      ]
    }else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any)
    }
    if (!form.value.judgeConfig){
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,}
    }else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any)
    }
    if (!form.value.tags){
      form.value.tags = []
    }else {
      form.value.tags = JSON.parse(form.value.tags as any)
    }
  }else {
    message.error('加载失败' + res.data.message)
  }
}
const handleAdd = () => {
  if (form.value.judgeCase){
    form.value.judgeCase.push({ input: '', output: '' });
  }
};

const handleDelete = (index: number) => {
  if (form.value.judgeCase){
    form.value.judgeCase.splice(index, 1);
  }
}
const doSubmit = async () => {
  // 如果是创建题目页面，就正常调用创建接口，如果是更新页面，就调用更新接口
  if (updatePage){
    const res = await updateQuestion(form.value)
    //console.log(res)
    if (res.data.code === 0){
      message.success('更新成功')
    }else {
      message.error('更新失败' + res.data.message)
    }
  }else {
    console.log(form.value)
    const res = await addQuestion(form.value)
    //console.log(res)
    if (res.data.code === 0){
      message.success('创建成功')
    }else {
      message.error('创建失败' + res.data.message)
    }
  }
}
const onContentChange = (value: string) => {
  form.value.content = value
}
const onAnswerChange = (value: string) => {
  form.value.answer = value
}
onMounted(() => {
  loadOldData()
})
</script>

<template>
  <div id="add-question" class="container">
    <header class="page-header">
      <h1 class="title">
        <a-typography style="color: var(--color-primary-6)">✦</a-typography>
        创建题目
      </h1>
    </header>

    <a-form
      :model="form"
      class="form-container"
      @submit="handleSubmit"
      label-align="left"
      size="large"
    >
      <!-- 标题 -->
      <a-form-item
        field="title"
        label="标题"
        :label-col-props="{ span: 3 }"
        :wrapper-col-props="{ span: 20 }"
      >
        <a-input
          v-model="form.title"
          placeholder="请输入标题"
          allow-clear
          class="input-with-shadow"
        />
      </a-form-item>

      <!-- 标签 -->
      <a-form-item
        field="tags"
        label="标签"
        :label-col-props="{ span: 3 }"
        :wrapper-col-props="{ span: 20 }"
      >
        <a-input-tag
          v-model="form.tags"
          placeholder="输入标签后按回车"
          allow-clear
          class="tag-input"
        />
      </a-form-item>

      <!-- 题目内容 -->
      <a-form-item
        field="content"
        label="题目内容"
        :label-col-props="{ span: 3 }"
        :wrapper-col-props="{ span: 20 }"
      >
        <MdEditor
          :value="form.content"
          class="md-editor"
          :height="360"
          style="min-width: 800px"
          :handle-change="onContentChange"
        />
      </a-form-item>

      <!-- 答案 -->
      <a-form-item
        field="answer"
        label="参考答案"
        :label-col-props="{ span: 3 }"
        :wrapper-col-props="{ span: 20 }"
      >
        <MdEditor
          :value="form.answer"
          class="md-editor"
          :height="280"
          style="min-width: 800px"
          :handle-change="onAnswerChange"
        />
      </a-form-item>

      <!-- 判题配置 -->
      <div class="config-section">
        <h3 class="section-title">
          <icon-settings class="section-icon" />
          判题配置
        </h3>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="时间限制">
              <a-input-number
                v-model="form.judgeConfig.timeLimit"
                placeholder="单位：ms"
                mode="button"
                class="config-input"
                :min="100"
                :step="100"
              >
                <template #suffix>ms</template>
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="内存限制">
              <a-input-number
                v-model="form.judgeConfig.memoryLimit"
                placeholder="单位：MB"
                mode="button"
                class="config-input"
                :min="128"
                :step="128"
              >
                <template #suffix>MB</template>
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="堆栈限制">
              <a-input-number
                v-model="form.judgeConfig.stackLimit"
                placeholder="单位：MB"
                mode="button"
                class="config-input"
                :min="64"
                :step="64"
              >
                <template #suffix>MB</template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 测试用例 -->
      <div class="test-case-section">
        <div class="section-header">
          <h3 class="section-title">
            <icon-code-square class="section-icon" />
            测试用例
          </h3>
          <a-button
            @click="handleAdd"
            type="primary"
            shape="round"
            class="add-btn"
          >
            <template #icon>
              <icon-plus />
            </template>
            新增用例
          </a-button>
        </div>

        <transition-group name="list">
          <div
            v-for="(caseItem, index) in form.judgeCase"
            :key="index"
            class="case-card"
          >
            <a-form-item
              :label="`用例 #${index + 1}`"
              :label-col-props="{ span: 3 }"
              :wrapper-col-props="{ span: 20 }"
            >
              <div class="case-content">
                <a-input
                  v-model="caseItem.input"
                  placeholder="输入用例（支持多行）"
                  allow-clear
                  type="textarea"
                  :auto-size="{ minRows: 2 }"
                />
                <a-input
                  v-model="caseItem.output"
                  placeholder="期望输出（支持多行）"
                  allow-clear
                  type="textarea"
                  :auto-size="{ minRows: 2 }"
                />
                <a-button
                  @click="handleDelete(index)"
                  shape="circle"
                  status="danger"
                  class="delete-btn"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </div>
            </a-form-item>
          </div>
        </transition-group>
      </div>

      <!-- 提交按钮 -->
      <a-form-item :wrapper-col-props="{ offset: 6 }">
        <a-button
          type="primary"
          html-type="submit"
          class="submit-btn"
          size="large"
          style="width:512px"
          @click="doSubmit"
        >
          <span class="submit-text">发布题目</span>
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style scoped>
.container {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
}

.page-header {
  margin-bottom: 3rem;
  text-align: center;
}

.title {
  font-size: 2rem;
  color: #333;
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: center;
}

.form-container {
  background: #fff;
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
}

.config-section, .test-case-section {
  margin: 2rem 0;
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 8px;
  transition: transform 0.2s;
}

.section-title {
  font-size: 1.1rem;
  color: #2c3e50;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-icon {
  color: var(--color-primary-6);
  font-size: 1.2em;
}

.config-input {
  width: 100%;
}

.test-case-section .section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.case-card {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 1rem;
  padding: 1rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  transition: all 0.3s ease;
  position: relative;
}

.case-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.delete-btn {
  position: absolute;
  right: -10px;
  top: -10px;
  opacity: 0;
  transition: opacity 0.2s;
}

.case-card:hover .delete-btn {
  opacity: 1;
}

.md-editor {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.submit-btn {
  margin-top: 2rem;
  height: 48px;
  font-weight: 500;
  transition: all 0.2s;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 153, 225, 0.3);
  text-align: center;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.3s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@media (max-width: 768px) {
  .container {
    padding: 1rem;
  }

  .form-container {
    padding: 1rem;
  }

  .config-section, .test-case-section {
    padding: 1rem;
  }
}
</style>
